package com.go.where.manager.service.impl;

import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import com.go.where.manager.common.Constants;
import com.go.where.manager.dao.AlbumDao;
import com.go.where.manager.page.Pagination;
import com.go.where.manager.page.BaseQuery.OrderType;
import com.go.where.manager.pojo.AlbumInfo;
import com.go.where.manager.pojo.user.UserInfoVO;
import com.go.where.manager.service.AlbumService;
import com.go.where.manager.util.CommonUtil;

@Service("albumService")
public class AlbumServiceImpl implements AlbumService {

	@Resource(name = "albumDao")
	private AlbumDao albumDao;

	@Override
	public AlbumInfo queryByPrimartKey(String cid) {
		return albumDao.getByKey(cid);
	}

	@Override
	public Pagination<AlbumInfo> queryPage(AlbumInfo albumInfo) {
		if (StringUtils.isNotEmpty(albumInfo.getOrderBy())
				&& albumInfo.getOrderType() != null) {
			if (albumInfo.getOrderType() == OrderType.asc) {
				albumInfo.setPage_orderByAsc(albumInfo.getOrderBy());

			} else {
				albumInfo.setPage_orderByDesc(albumInfo.getOrderBy());
			}
		}
		Long totalSupport = albumDao.queryTotalSupport(albumInfo);
		Integer count = albumDao.totalCount(albumInfo);
		albumInfo.calculate();
		List<AlbumInfo> list = albumDao.queryList(albumInfo);
		if (list != null && !list.isEmpty()) {
			for (AlbumInfo info : list) {
				if (totalSupport != null && totalSupport.longValue() != 0) {
					Double rate = CommonUtil.div(info.getSupportNum(), totalSupport).doubleValue();
					info.setSupportRate(rate);
				}
			}
		}
		Pagination<AlbumInfo> page = albumDao.queryPagination(count, list, albumInfo);
		return page;
	}

	@Override
	public int save(AlbumInfo albumInfo, UserInfoVO currentUser) {
		albumInfo.setPublishTime(new Date());
		albumInfo.setUserId(currentUser.getUserId());
		albumInfo.setIsDelete(Constants.NOT_DELETED);
		return albumDao.insert(albumInfo);
	}

	@Override
	public int update(AlbumInfo albumInfo, UserInfoVO currentUser) {
		albumInfo.setUpdateTime(new Date());
		albumInfo.setUserId(currentUser.getUserId());
		return albumDao.update(albumInfo);
	}

	@Override
	public List<AlbumInfo> queryAll() {
		return albumDao.queryAll();
	}

}
